package db

import (
	"path/filepath"
	"sync"
	"time"

	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/sqlite"
	"github.com/sirupsen/logrus"
)

var dbMap = map[string]*gorm.DB{}
var syncLock sync.Mutex
var dbIns *gorm.DB

func init() {
	initDB("litetalk")
	dbIns = GetDb("litetalk")
	dbIns.AutoMigrate(&IMUser{}, &IMGroup{}, &IMDepart{}, &IMGroupMember{}, &IMSlave{})
	for _, m := range messageArray {
		dbIns.AutoMigrate(m)
	}

	depart := &IMDepart{
		Name:     "Unknown",
		ParentId: 0,
		Status:   0,
	}
	depart.Add()

	robot := &IMUser{}
	robot.UserName = "系统消息"
	robot.NickName = "系统消息"
	robot.Password = "你瞧不出来的密码"
	robot.SignInfo = "系统消息，请勿回复"
	robot.Add()
}

func initDB(dbName string) {
	var e error
	realPath, _ := filepath.Abs(".")
	configFilePath := realPath + "/db/litetalk.sqlite3"
	syncLock.Lock()
	dbMap[dbName], e = gorm.Open("sqlite3", configFilePath)
	dbMap[dbName].DB().SetMaxIdleConns(4)
	dbMap[dbName].DB().SetMaxOpenConns(20)
	dbMap[dbName].DB().SetConnMaxLifetime(8 * time.Second)
	syncLock.Unlock()
	if e != nil {
		logrus.Errorf("connect db fail:", e.Error())
	}
}

func GetDb(dbName string) *gorm.DB {
	if db, ok := dbMap[dbName]; ok {
		return db
	} else {
		return nil
	}
}
